import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import {
  fetchAllConservations,
  fetchConservationList,
  fetchConservationDetail,
  createConservation,
  updateConservation,
  deleteConservation, generateAnswer,
} from '@/services/conservationService';
import {ConservationDetail, ConservationPagination, ConservationRes, ConservationState} from "@/types/conservationType";

const initialState: ConservationState = {
    conservations: {
        items: [],
        total: 0,
        page: 1,
        size: 10,
        total_pages: 0,
        links: []
    },
    generating: false,
    generatingTask: null,
    conservationDetail: null,
    status: 'idle',
    error: null,
};

// Conservation slice
const conservationSlice = createSlice({
    name: 'conservation',
    initialState,
    reducers: {
        // Reset conservation information
        resetConservationInfo: (state) => {
            state.conservations = {
                items: [],
                total: 0,
                page: 1,
                size: 10,
                total_pages: 0,
                links: []
            };
            state.generating= false;
            state.generatingTask = null;
            state.conservationDetail = null;
            state.status = 'idle';
            state.error = null;
        },
        // Set partial conservation information
        setConservationInfo: (state, action: PayloadAction<Partial<ConservationRes>>) => {
            if (state.conservationDetail) {
                state.conservationDetail = { ...state.conservationDetail, ...action.payload };
            }
        },

        setConservationStateInfo: (state, action: PayloadAction<Partial<ConservationState>>) => {
          Object.assign(state, action.payload);
        },

        // Set partial conservation information
        setConservationAnswerInfo: (state, action: PayloadAction<any[]>) => {
          if (state.conservationDetail) {
            const len = state.conservationDetail.chat_history.length;
            // 使用 Array.from 创建数组的浅拷贝
            const res = Array.from(action.payload);
            state.conservationDetail.chat_history[len - 1].contents = res[0];
          }
        },
    },
    extraReducers: (builder) => {
        // Fetch all conservations
        builder
            .addCase(fetchAllConservations.pending, (state) => {
                state.status = 'loading';
                state.conservations.items = []
            })
            .addCase(fetchAllConservations.fulfilled, (state, action) => {
                state.status = 'succeeded';
                state.conservations.items = action.payload;
            })
            .addCase(fetchAllConservations.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
            });

        // Fetch conservation list (paginated)
        builder
            .addCase(fetchConservationList.pending, (state) => {
                state.status = 'loading';
            })
            .addCase(fetchConservationList.fulfilled, (state, action: PayloadAction<ConservationPagination>) => {
                state.status = 'succeeded';
                state.conservations = action.payload;
            })
            .addCase(fetchConservationList.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
            });

        // Fetch conservation details
        builder
            .addCase(fetchConservationDetail.pending, (state) => {
                state.status = 'loading';
            })
            .addCase(fetchConservationDetail.fulfilled, (state, action: PayloadAction<ConservationDetail>) => {
                state.status = 'succeeded';
                state.conservationDetail = action.payload;
            })
            .addCase(fetchConservationDetail.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
            });

        // Create a new conservation
        builder
            .addCase(createConservation.pending, (state) => {
                state.status = 'loading';
            })
            .addCase(createConservation.fulfilled, (state, action: PayloadAction<ConservationRes>) => {
              state.status = 'succeeded';
              // 将新创建的会话添加到会话列表的最前面
              state.conservations.items = [action.payload, ...state.conservations.items];
              // 返回新的状态，而不是 action.payload
              return state;
            })
            .addCase(createConservation.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
            });

        // Update conservation information
        builder
            .addCase(updateConservation.pending, (state) => {
                state.status = 'loading';
            })
            .addCase(updateConservation.fulfilled, (state) => {
                state.status = 'succeeded';
            })
            .addCase(updateConservation.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
            });

        // Delete conservations
        builder
            .addCase(deleteConservation.pending, (state) => {
                state.status = 'loading';
            })
            .addCase(deleteConservation.fulfilled, (state, action) => {
                state.status = 'succeeded';
                state.conservations.items = state.conservations.items.filter(
                    (conservation) => action.payload !== conservation.uuid
                );
            })
            .addCase(deleteConservation.rejected, (state, action) => {
                state.status = 'failed';
                state.error = action.payload as string;
            });

        builder
            .addCase(generateAnswer.pending, (state) => {
                state.generating = true
            })
            .addCase(generateAnswer.fulfilled, (state, action) => {
                state.generatingTask = action.payload
            })
            .addCase(generateAnswer.rejected, (state, action) => {
                state.error = action.payload as string;
                state.generating = false
            });
    },
});

// Export actions
export const { resetConservationInfo, setConservationInfo, setConservationStateInfo, setConservationAnswerInfo} = conservationSlice.actions;

// Export reducer
export default conservationSlice.reducer;
